//
//  NetworkingHandle.m
//  IYoker_Organization
//
//  Created by chunjian Dai on 15/12/19.
//  Copyright © 2015年 wangguimin. All rights reserved.
//

#import "NetworkingHandle.h"
#import "NSString+secure.h"
#import "HsSecureHander.h"
#import "JSONKit.h"
#import "LoginViewController.h"
#import "NSObject+NetworkingState.h"

static NSMutableArray *taskArray;

@interface NetworkingHandle ()


@end

@implementation NetworkingHandle
- (NSMutableArray *)taskArray{
    if (!_taskArray) {
        self.taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

+ (instancetype)sharedNetManager
{
    static NetworkingHandle *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[self alloc] init];
    });
    return handle;
}

+ (AFHTTPSessionManager *)sharedmanager{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain",@"text/javascript", @"text/html",@"multipart/form-data", nil];
        //        ((AFJSONResponseSerializer *)_manager.responseSerializer).removesKeysWithNullValues = YES;
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        manager.requestSerializer.timeoutInterval = 20;

    });
    return manager;
}

- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        self.manager = [NetworkingHandle sharedmanager];

        [_manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    return _manager;
}
- (AFSecurityPolicy *)customSecurityPolicy
{
    /*
    //先导入证书，找到证书的路径
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"oral" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    //AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:certData, nil]];
    securityPolicy.allowInvalidCertificates = NO;
    securityPolicy.validatesDomainName = YES;
     */
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    return securityPolicy;
}

- (void)postNetworkingWithURL:(NSString *)URL
                   parameters:(NSDictionary *)parameters
                         type:(NetWorkingType)type
                     delegate:(id<NetworkingHandleDelegate>)delegate{
//    if (![URL containsString:NET_FINDSTATISISC]) {
//        [self showIndeterminate];
//    }
//    ! 检查地址中是否有中文 
    NSString *URLString = [NSURL URLWithString:URL] ? URL : [self strUTF8Encoding:URL];
    @weakify(self);
    NSURLSessionTask *sessionTask = [self.manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        
        if (!self.firstNetwork) {
            self.firstNetwork = YES;
            [self postNotificationName:kNotificationFirstNetwork object:nil];
        }
        
        [self.taskArray removeObject:sessionTask];
        [self hideHud];
        [self logWithParam:parameters url:URLString response:responseObject type:type];
        if ([responseObject[@"returnNo"] isEqualToString: OR_SUCCESS]) {
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleSuccess: parameters: responseObject: type:)]) {
                if ([responseObject[@"secure"] integerValue] == 1) {
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:[self dictionaryWithJsonString:[responseObject[@"content"] decoder]] type:type];
                } else {
                    
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:responseObject[@"content"] type:type];
                }
            }
        } else {
            
            if ([self isShowWarningWithReturnNo:responseObject[@"returnNo"]]) {
                
                [self showWindowHint:responseObject[@"returnInfo"] imageStr:@"warning"];

            }
            
            
            if ([responseObject[@"returnNo"] isEqualToString:@"0031"]) {
                
                LoginViewController *VC = [[LoginViewController alloc] init];
                
                WGMNavigationController *naviC = [[WGMNavigationController alloc] initWithRootViewController:VC];
                [[UIApplication sharedApplication] delegate].window.rootViewController = naviC;
                
                [self removeUserLoginInfo];                
                [self postNotificationName:kNotificationNOLOGIN object:self userInfo:@{@"content":responseObject[@"returnInfo"]}];
            
            }
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleWarning: responseObject: type:)]) {
                
                [delegate networkingHandleWarning:self responseObject:responseObject type:type];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self);
        [self.taskArray removeObject:sessionTask];
        [self networkingFailWithError:error delegate:delegate type:type];
    }];
    
    if (sessionTask)
    {
        [self.taskArray addObject:sessionTask];
    }
}
- (void)logWithParam:(NSDictionary *)param
                 url:(NSString *)url
            response:(id)response
                type:(NetWorkingType)type
{
    NSArray *stateArray = @[@"请求成功",[NSString stringWithFormat:@"请求警告为%@",response[@"returnNo"]]];
    NSString *stateStr = [response[@"returnNo"] integerValue] ? stateArray[1] : stateArray[0];
    if ([response[@"secure"] integerValue]) {
        NSLog(@"\n--------%@:-----------\n请求type: NetWorkingType%lu\n请求URL: %@\n请求参数: %@\n返回结果：%@\n--------请求结束-----------",stateStr,(unsigned long)type,url,[self dictionaryWithJsonString:[param[@"content"] decoder]],[self dictionaryWithJsonString:[response[@"content"] decoder]]);
    } else {
        NSLog(@"\n--------%@:-----------\n请求type: NetWorkingType%lu\n请求URL: %@\n请求参数: %@\n返回结果：%@\n--------请求结束-----------",stateStr,(unsigned long)type,url,param,response[@"content"]);
    }
    
}

//  不显示提示框的报错
- (BOOL)isShowWarningWithReturnNo:(NSString *)returnNo{
    if ([returnNo isEqualToString:@"0020"]|| [returnNo isEqualToString:@"0036"] || [returnNo isEqualToString:@"0022"] || [returnNo isEqualToString:@"0032"] || [returnNo isEqualToString:@"0047"]|| [returnNo isEqualToString:@"0055"] || [returnNo isEqualToString:@"0051"]) {
        return NO;
    }
   
    return YES;
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
+ (id)handleDownWithURL:(NSString *)URL
         path:(NSString *)path
           delegate:(id<NetworkingHandleDelegate>)delegate
               type:(NetWorkingType)type{
    
    return [[[self class] alloc] initDownWithURL:URL path:path delegate:delegate type:type];
    
}
- (id)initDownWithURL:(NSString *)URL
             path:(NSString *)path
         delegate:(id<NetworkingHandleDelegate>)delegate
             type:(NetWorkingType)type{
    self = [super init];
    if (self) {
        [self downLoadWithURL:URL path:path type:type delegate:delegate];
    }
    return self;
}

- (void)downLoadWithURL:(NSString *)URL
                   path:(NSString *)path
                   type:(NetWorkingType)type
               delegate:(id<NetworkingHandleDelegate>)delegate{
    
    //3.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
    @weakify(self);
    //下载任务
    NSURLSessionDownloadTask *task = [self.manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        @strongify(self);
        if (delegate && [delegate respondsToSelector:@selector(networkingHandle:downloadProgress:type:)]) {
            [delegate networkingHandle:self downloadProgress:downloadProgress type:type];
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //下载地址
        NSLog(@"默认下载地址:%@",targetPath);
        
        //设置下载路径，通过沙盒获取缓存地址，最后返回NSURL对象
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        return [NSURL URLWithString:filePath];
        
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        //下载完成调用的方法
        NSLog(@"下载完成：");
        NSLog(@"%@--%@",response,filePath);
        
    }];
    
    //开始启动任务
    [task resume];
    
}

/*
+ (id)handleWithURL:(NSString *)URL
         parameters:(NSDictionary *)parameters
         imageArray:(NSArray *)imageArray
 compressionQuality:(CGFloat)compressionQuality
           delegate:(id<NetworkingHandleDelegate>)delegate
               type:(NetWorkingType)type
{
    return [[[self class] alloc] initWithURL:URL parameters:parameters imageArray:imageArray compressionQuality:compressionQuality delegate:delegate type:type];
}

*/


- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image, 1.0f);
        mimeType = @"image/jpeg";
    }
    
    return [NSString stringWithFormat:@"%@",
            [imageData base64EncodedStringWithOptions: 0]];
    
}

- (void)postNetworkingWithURL:(NSString *)URL
                 imagePicName:(NSString *)imagePicName
                   image:(UIImage *)image
                   parameters:(NSDictionary *)parameters
                         type:(NetWorkingType)type
                     delegate:(id<NetworkingHandleDelegate>)delegate{
//    [self showIndeterminate];
    NSString *URLString = [NSURL URLWithString:URL] ? URL : [self strUTF8Encoding:URL];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:parameters];

    NSString *data = [self image2DataURL:image];
    
    params[imagePicName] = data;
    @weakify(self);
    NSURLSessionTask *sessionTask = [self.manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        [self.taskArray removeObject:sessionTask];
        [self hideHud];
        if ([responseObject[@"returnNo"] isEqualToString: OR_SUCCESS]) {
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleSuccess: parameters: responseObject: type:)]) {
                if ([responseObject[@"secure"] integerValue] == 1) {
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:[self dictionaryWithJsonString:[responseObject[@"content"] decoder]] type:type];
                } else {
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:responseObject[@"content"] type:type];
                }
            }
        } else {
            
            if ([self isShowWarningWithReturnNo:responseObject[@"returnNo"]]) {
                
                [self showWindowHint:responseObject[@"returnInfo"] imageStr:@"warning"];
                
            }
            
            
            if ([responseObject[@"returnNo"] isEqualToString:@"0031"]) {
                
                LoginViewController *VC = [[LoginViewController alloc] init];
                
                WGMNavigationController *naviC = [[WGMNavigationController alloc] initWithRootViewController:VC];
                [[UIApplication sharedApplication] delegate].window.rootViewController = naviC;
                
                [self removeUserLoginInfo];
                [self postNotificationName:kNotificationNOLOGIN object:self userInfo:@{@"content":responseObject[@"returnInfo"]}];
                
            }
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleWarning: responseObject: type:)]) {
                
                [delegate networkingHandleWarning:self responseObject:responseObject type:type];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self);
        [self.taskArray removeObject:sessionTask];
        [self networkingFailWithError:error delegate:delegate type:type];
    }];
    
    if (sessionTask)
    {
        [self.taskArray addObject:sessionTask];
    }
    
}

- (void)postNetworkingWithURL:(NSString *)URL
                 imagePicName:(NSString *)imagePicName
                        imageArray:(NSArray *)imageArray
                   parameters:(NSDictionary *)parameters
                         type:(NetWorkingType)type
                     delegate:(id<NetworkingHandleDelegate>)delegate{
    
//    [self showIndeterminate];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    
    NSMutableString *dataStr = [NSMutableString string];
    
    for (int i = 0; i < imageArray.count; i++) {
        NSString *str = [self image2DataURL:imageArray[i]];
        [dataStr appendFormat:@"%@,",str];
        
    }
    
    if (dataStr.length) {
        [dataStr deleteCharactersInRange:NSMakeRange(dataStr.length - 1, 1)];
        params[imagePicName] = dataStr;
    } else {
        params[imagePicName] = @"";
    }
    
    @weakify(self);
    [self.manager POST:URL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [self hideHud];
        @strongify(self);
        NSLog(@"返回结果：%@",responseObject);
        
        if ([responseObject[@"returnNo"] isEqualToString: OR_SUCCESS]) {
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleSuccess: parameters: responseObject: type:)]) {
                if ([responseObject[@"secure"] integerValue] == 1) {
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:[self dictionaryWithJsonString:[responseObject[@"content"] decoder]] type:type];
                } else {
                    [delegate networkingHandleSuccess:self parameters:parameters responseObject:responseObject[@"content"] type:type];
                }
            }
        } else {
            
            if ([self isShowWarningWithReturnNo:responseObject[@"returnNo"]]) {
//                [self showWindowHint:responseObject[@"returnInfo"] imageStr:@"warning"];
                
            }
            
            if (delegate && [delegate respondsToSelector:@selector(networkingHandleWarning: responseObject: type:)]) {
                
                [delegate networkingHandleWarning:self responseObject:responseObject type:type];
                
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        @strongify(self);
        [self networkingFailWithError:error delegate:delegate type:type];
    }];
    
}
//  网络请求失败的处理方法
- (void)networkingFailWithError:(NSError *)error delegate:(id<NetworkingHandleDelegate>)delegate type:(NetWorkingType)type{
 
    [self hideHud];
    
    NSLog(@"网络请求失败了       -----          %@",error.description);
    if (self.netState == AFNetworkReachabilityStatusNotReachable) {
        [self showErrorWithStatus:@"网络连接不可用，请检查网络"];
    } else {
        [self showErrorWithStatus:@"请检查网络或稍后重试"];
    }
    if (delegate && [delegate respondsToSelector:@selector(networkingHandlefail: type:)]) {
        [delegate networkingHandlefail:self type:type];
    }
}

- (NSString *)strUTF8Encoding:(NSString *)str
{
    /*! ios9适配的话 打开第一个 */
    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
//    return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end
